package com.game.tictactoe;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 比赛
 *
 * @Author xuehuanwu
 * @Date 2021/10/19 20:30
 * @Version 1.0
 */
public class Play {

    public static final String[] attrR = {"X", "O"};
    public static final String[][] attrN = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}};

    public static void main(String[] args) {
        List<User> userList = initUser();
        String str = "y";
        while ("y".equalsIgnoreCase(str)) {
            String[][] attr = {attrN[0].clone(), attrN[1].clone(), attrN[2].clone()};
            play(userList, attr);
            printUser(userList);
            System.out.print("try again! please input y/n: ");
            Scanner in = new Scanner(System.in);
            str = in.nextLine();
        }
    }

    /**
     * 初始化用户
     *
     * @return
     */
    private static List<User> initUser() {
        List<User> userList = new ArrayList<User>();
        for (int i = 0; i < attrR.length; i++) {
            System.out.print("Enter Player " + attrR[i] + " name: ");
            Scanner in = new Scanner(System.in);
            User user = new User();
            user.setUserName(in.nextLine());
            user.setRoleName(attrR[i]);
            userList.add(user);
        }
        return userList;
    }

    /**
     * 玩游戏
     *
     * @param userList
     * @param attr
     */
    private static void play(List<User> userList, String[][] attr) {
        while (true) {
            for (User user : userList) {
                do {
                    inputNum(user);
                } while (null == Rule.choiceAttr(attr, user));
                Rule.printAttr(attr);
                if (Rule.initRule(attr)) {
                    System.out.println(user.getUserName() + " wins!");
                    user.setWinNum(user.getWinNum() + 1);
                    return;
                }
            }
        }
    }

    /**
     * 输入值
     *
     * @param user
     */
    private static void inputNum(User user) {
        System.out.print("Please enter your choice player " + user.getRoleName() + ": ");
        Scanner in = new Scanner(System.in);
        user.setInputNum(Rule.checkInput(in.nextLine()));
    }

    /**
     * 打印用户
     *
     * @param userList
     */
    private static void printUser(List<User> userList) {
        userList.stream().forEach(user -> {
            System.out.println(user.getUserName() + " | " + user.getWinNum());
        });
    }
}
